package com.zhangsun.yueBoot.framework.handler;

import com.alibaba.fastjson.JSON;
import com.zhangsun.yueBoot.commons.base.bean.ResponseResult;
import com.zhangsun.yueBoot.commons.tools.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登出成功
 */
@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {

    @Value("${jwt.header}")
    private String header;

    @Value("${jwt.tokenType}")
    private String tokenType;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setStatus(200);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = httpServletResponse.getWriter();

        String authHeader = httpServletRequest.getHeader(header);
        if (authHeader != null && authHeader.startsWith(tokenType)) {
            String authToken = authHeader.substring(tokenType.length());
            jwtTokenUtil.del(authToken);
        }

        ResponseResult responseResult = ResponseResult.error("200", "登出成功");
        printWriter.write(JSON.toJSONString(responseResult));
        printWriter.flush();
    }

}
